package schoolsource.gui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.logging.Level;

import javax.servlet.http.HttpServletRequest;

import schoolsource.config.ConfigurationItems;
import schoolsource.model.AttachmentContainer;
import schoolsource.model.ClassContainer;
import schoolsource.model.ContactContainer;
import schoolsource.model.CourseContainer;
import schoolsource.model.HomeworkContainer;
import schoolsource.model.Item;
import schoolsource.model.MessageContainer;
import schoolsource.model.PairedUserContainer;
import schoolsource.model.PasswordItem;
import schoolsource.model.StringItem;
import schoolsource.model.SubmissionContainer;
import schoolsource.model.TermContainer;
import schoolsource.model.UserContainer;
import schoolsource.sql.SchoolDBSQL;
import schoolsource.util.SchoolLogger;

/**
 *
 * @author Steven Steele
 * Copyright 2003
 *
 * Translates form input into containers, lists, or other recognized formats
 */
public class FormParser extends FormFields {

/**
   * Parses information from a form into the passed-in container
   * @param formData The data from the form.
   * @param courseContainer The container to parse into.
   */
  public static void updateCourse(HttpServletRequest formData, CourseContainer courseContainer) {
    courseContainer.getCourseAssignedID().setValue(formData.getParameter(SchoolDBSQL.COURSEASSIGNEDID));
    courseContainer.getCourseSchoolID().setValue(formData.getParameter(SchoolDBSQL.COURSESCHOOLID));
    courseContainer.getCourseDescription().setValue(formData.getParameter(SchoolDBSQL.COURSEDESCRIPTION));
    courseContainer.getCourseShortName().setValue(formData.getParameter(SchoolDBSQL.COURSESHORTNAME));
  }

  /**
   * Parses information from a form into the passed-in container
   * @param formData The data from the form.
   * @param classContainer The container to parse into.
   */
  public static void updateClass(HttpServletRequest formData, ClassContainer classContainer, String dbName) {
    classContainer.getClassAssignedID().setValue(formData.getParameter(SchoolDBSQL.CLASSASSIGNEDID));
    classContainer.getClassSchoolID().setValue(formData.getParameter(SchoolDBSQL.CLASSSCHOOLID));
    classContainer.getClassTime().setValue(formData.getParameter(SchoolDBSQL.CLASSTIME));
//    classContainer.setAssociatedCourse(new CourseContainer(formData.getParameter(SchoolDBSQL.COURSEASSIGNEDID)));
    classContainer.getCourseAssignedID().setValue(formData.getParameter(SchoolDBSQL.COURSEASSIGNEDID));
    classContainer.setAssociatedCourse(CourseContainer.getCourseContainer(classContainer.getCourseAssignedID().toString(), dbName));
//  classContainer.setAssociatedCourse(CourseContainer.getCourseContainer(formData.getParameter(SchoolDBSQL.COURSEASSIGNEDID), dbName));
  }

  /**
   * Parses information from a form into the passed-in container
   * @param formData The data from the form.
   * @param classContainer The container to parse into.
   */
  public static void updateTerm(HttpServletRequest formData, TermContainer termContainer, String dbName) {
    termContainer.getTermName().setValue(formData.getParameter(SchoolDBSQL.TERMNAME));
    termContainer.getTermStartDay().setValue(formData.getParameter(SchoolDBSQL.TERMSTART));
    termContainer.getTermEndDay().setValue(formData.getParameter(SchoolDBSQL.TERMEND));
  }

    /**
     * Saves an attachment included with a form and associates it with a homework container.
     * @param formData The data from the form.
     * @param homeworkContainer The container with which the attachment is associated.
     * @param subPath The path where the file should be saved.
     */
    public static void updateAttachment(HttpServletRequest formData, HomeworkContainer homeworkContainer, String subPath, String dbName) throws IOException {

        // fileName is the name of the original file from the user.
        String fileName = formData.getParameter(SchoolDBSQL.ATTFILENAME+".filename");
        if ("".equals(fileName)) {
            return;
        }
        fileName = fileName.substring(fileName.lastIndexOf('/') + 1); // get rid of any UNIX path directories
        fileName = fileName.substring(fileName.lastIndexOf('\\') + 1); // get rid of any windows path directories

        // tempFileName is the path and filename that Multipart store on the server.
        String tempFileName = formData.getParameter(SchoolDBSQL.ATTFILENAME+".file");

        AttachmentContainer attachmentContainer = AttachmentContainer.getAttachmentContainer("-1", dbName);

        SchoolLogger.logger.log(Level.INFO, "In Attach code........subPath is " + subPath + "..........");
        SchoolLogger.logger.log(Level.INFO, "In Attach code........homeworkID is " + homeworkContainer.getHomeworkID() + "..........");
        SchoolLogger.logger.log(Level.INFO, "In Attach code........fileName is " + fileName + "..........");
        SchoolLogger.logger.log(Level.INFO, "In Attach code........tempFileName is " + tempFileName + "..........");
        String newFileName = "";

        try {
            File newFile = new File(fileName);
            newFileName = newFile.getName();

            FileInputStream is = new FileInputStream(tempFileName);
//          attachmentContainer.getFilePath().setValue("attachments\\" + subPath + "\\" + homeworkContainer.getHomeworkID() + "\\");
//          attachmentContainer.getFilePath().setValue("attachments/" + subPath + "/" + homeworkContainer.getHomeworkID() + "/");
            attachmentContainer.getFilePath().setValue("attachments" + ConfigurationItems.PATHSEPARATOR + subPath + ConfigurationItems.PATHSEPARATOR + homeworkContainer.getHomeworkID() + ConfigurationItems.PATHSEPARATOR);

            // the path for the output file needs 'doc' prepended to it because incoming file requests use a
            // different file path than that used by the servlet
//          File newOutFilePath = new File("doc\\"+attachmentContainer.getFilePath().toString());
//          File newOutFilePath = new File(attachmentContainer.getFilePath().toString());
//          File newOutFilePath = new File("/home/mystud2/public_html/" + attachmentContainer.getFilePath().toString());
            File newOutFilePath = new File(ConfigurationItems.BASEPATH + attachmentContainer.getFilePath().toString());

            boolean returnValue = newOutFilePath.mkdir();


//          File saveFilePath = new File("doc\\"+attachmentContainer.getFilePath().toString() + newFileName);
//          File saveFilePath = new File(attachmentContainer.getFilePath().toString() + newFileName);
//          File saveFilePath = new File("/home/mystud2/public_html/" + attachmentContainer.getFilePath().toString() + newFileName);
            File saveFilePath = new File(ConfigurationItems.BASEPATH + attachmentContainer.getFilePath().toString() + newFileName);

            FileOutputStream out = new FileOutputStream(saveFilePath);

            int ch;
            while ((ch = is.read()) >= 0){
                out.write((char) ch);
            }

            is.close();
            out.close();

            attachmentContainer.getAssignedAttachmentID().setValue(formData.getParameter(SchoolDBSQL.ATTASSIGNEDID));
            attachmentContainer.getFileName().setValue(newFileName);

            attachmentContainer.getFileSize().setValue("" + saveFilePath.length());
            homeworkContainer.addAttachment(attachmentContainer);
        }
        catch (IOException ioe) {
            SchoolLogger.logger.log(Level.WARNING, "Could not save file: " + ioe);
            throw ioe;
        }

    }


    public static void updateSubmission(HttpServletRequest formData, HomeworkContainer homeworkContainer, UserContainer userContainer, String subPath, String dbName) throws IOException {

        // fileName is the user id plus the extension of the original file
        String originalFileName = formData.getParameter(SchoolDBSQL.SUBMISSIONFILENAME+".filename");
        originalFileName = originalFileName.substring(originalFileName.lastIndexOf('/') + 1); // get rid of any UNIX path directories
        originalFileName = originalFileName.substring(originalFileName.lastIndexOf('\\') + 1); // get rid of any windows path directories

        // tempFileName is the path and filename that Multipart store on the server.
        String tempFileName = formData.getParameter(SchoolDBSQL.SUBMISSIONFILENAME+".file");
        String newFileName = "";

        int extStart = originalFileName.lastIndexOf(".");
        if (extStart < 0) {
            newFileName = userContainer.getAssignedID().toString();
        }
        else {
            newFileName = userContainer.getAssignedID() + originalFileName.substring(extStart);
        }

//        SubmissionContainer submissionContainer = SubmissionContainer.getSubmissionContainer("-1", "-1", "-1", dbName);
        SubmissionContainer submissionContainer = SubmissionContainer.getSubmissionContainer(homeworkContainer.getClassID().toString(),
                                                                                             homeworkContainer.getHomeworkID().toString(),
                                                                                             userContainer.getAssignedID().toString(), dbName);

        SchoolLogger.logger.log(Level.INFO, "In Attach code........subPath is " + subPath + "..........");
        SchoolLogger.logger.log(Level.INFO, "In Attach code........classID is " + homeworkContainer.getClassID() + "............");
        SchoolLogger.logger.log(Level.INFO, "In Attach code........homeworkID is " + homeworkContainer.getHomeworkID() + "..........");
        SchoolLogger.logger.log(Level.INFO, "In Attach code........userID is " + userContainer.getAssignedID() + "..........");
        SchoolLogger.logger.log(Level.INFO, "In Attach code........originalFileName is " + originalFileName + "..........");
        SchoolLogger.logger.log(Level.INFO, "In Attach code........newFileName is " + newFileName + "..........");
        SchoolLogger.logger.log(Level.INFO, "In Attach code........tempFileName is " + tempFileName + "..........");

        try {
            File newFile = new File(newFileName);
            newFileName = newFile.getName();

            FileInputStream is = new FileInputStream(tempFileName);
            String dirPath = "attachments" + ConfigurationItems.PATHSEPARATOR + subPath + ConfigurationItems.PATHSEPARATOR +
                                                homeworkContainer.getHomeworkID() + ConfigurationItems.PATHSEPARATOR;

            // the path for the output file needs 'doc' prepended to it because incoming file requests use a
            // different file path than that used by the servlet
            File newOutFilePath = new File(ConfigurationItems.BASEPATH + dirPath);
            boolean returnValue = newOutFilePath.mkdir();
            if (!returnValue) {
                SchoolLogger.logger.log(Level.INFO, "In Attach code........Could not create homework directory");
            }

            String subdirPath = dirPath + "submissions" + ConfigurationItems.PATHSEPARATOR;

            File subdir = new File(ConfigurationItems.BASEPATH + subdirPath);
            submissionContainer.getFilePath().setValue(subdirPath);
            returnValue = subdir.mkdir();
            if (!returnValue) {
                SchoolLogger.logger.log(Level.INFO, "In Attach code........Could not create submission directory");
            }


            File saveFilePath = new File(ConfigurationItems.BASEPATH + submissionContainer.getFilePath().toString() + newFileName);

            FileOutputStream out = new FileOutputStream(saveFilePath);

            int ch;
            while ((ch = is.read()) >= 0){
                out.write((char) ch);
            }

            is.close();
            out.close();

            submissionContainer.getAssignedClassID().setValue(homeworkContainer.getClassID().toString());
            submissionContainer.getAssignedHomeworkID().setValue(homeworkContainer.getHomeworkID().toString());
            submissionContainer.getAssignedStudentID().setValue(userContainer.getAssignedID().toString());
            submissionContainer.getFileName().setValue(newFileName);
            submissionContainer.getSubmissionDate().setTrueValue(new GregorianCalendar());

            submissionContainer.getFileSize().setValue("" + saveFilePath.length());

            SchoolDBSQL.getSchoolDBSQL(dbName).save(submissionContainer);

            // TODO set updateAllowed as appropriate
        }
        catch (IOException ioe) {
            SchoolLogger.logger.log(Level.WARNING, "Could not save file: " + ioe);
            throw ioe;
        }

    }


    /**
     * Parses communications from the passed-in data and returns an array of contacts for
     * each sender-recipient pair.
     * @param formData The data from the form.
     * @return Contact containers containing message information from the form.
     */
// TODO This does not seem to be used
    private static ContactContainer[] sendCommunications(HttpServletRequest formData, String dbName) {
        ContactContainer comm1= null;// = new ContactContainer();
        ContactContainer comm2 = null;
//      comm1.getMessageAssignedID().setValue(formData.getParameter(SchoolDBSQL.MSGASSIGNEDID));
//      comm1.getClassAssignedID().setValue(formData.getParameter(SchoolDBSQL.CLASSASSIGNEDID));
//      comm1.getFromID().setValue(formData.getParameter(SchoolDBSQL.CTFROMID));
//      comm1.getMessage().getSubject().setValue(formData.getParameter(SchoolDBSQL.MSGSUBJECT));
//      comm1.getMessage().getMessageBody().setValue(formData.getParameter(SchoolDBSQL.MSGBODY));
//      comm1.getMessage().getDateTimeSent().setTrueValue(new GregorianCalendar());

        String toParent = formData.getParameter(PARENTCHECKBOX);
        String parentID = formData.getParameter(PARENTASSIGNEDID);
        String toStudent = formData.getParameter(STUDENTCHECKBOX);
        String studentID = formData.getParameter(STUDENTASSIGNEDID);
        // if it is coming from the teacher, at least one of these should not be null
        if (toParent != null || toStudent != null) {
            PairedUserContainer puc =
                PairedUserContainer.getPairedContainer(
                    formData.getParameter(SchoolDBSQL.CTTOID), dbName);
            if ("TRUE".equals(toParent)) {
                if ("TRUE".equals(toStudent)) { // to both
//                  comm1.getToID().setValue(puc.getParentID().toString());
                    comm1 = ContactContainer.getContactContainer(formData.getParameter(SchoolDBSQL.MSGASSIGNEDID),
                                                                 puc.getParentID().toString(),
                                                                 formData.getParameter(SchoolDBSQL.CTFROMID),
                                                                 dbName);
                    comm1.getClassAssignedID().setValue(formData.getParameter(SchoolDBSQL.CLASSASSIGNEDID));
                    comm1.getMessage().getSubject().setValue(formData.getParameter(SchoolDBSQL.MSGSUBJECT));
                    comm1.getMessage().getMessageBody().setValue(formData.getParameter(SchoolDBSQL.MSGBODY));
                    comm1.getMessage().getDateTimeSent().setTrueValue(new GregorianCalendar());

                    comm2 = ContactContainer.getContactContainer(formData.getParameter(SchoolDBSQL.MSGASSIGNEDID),
                                                                 puc.getStudentID().toString(),
                                                                 formData.getParameter(SchoolDBSQL.CTFROMID),
                                                                 dbName);
//                  comm2 = new ContactContainer();
//                  comm2.getMessageAssignedID().setValue(
//                      formData.getParameter(SchoolDBSQL.MSGASSIGNEDID));
                    comm2.getClassAssignedID().setValue(
                        formData.getParameter(SchoolDBSQL.CLASSASSIGNEDID));
//                  comm2.getToID().setValue(puc.getStudentID().toString());
//                  comm2.getFromID().setValue(
//                      formData.getParameter(SchoolDBSQL.CTFROMID));
                    comm2.getMessage().getSubject().setValue(
                        formData.getParameter(SchoolDBSQL.MSGSUBJECT));
                    comm2.getMessage().getMessageBody().setValue(
                        formData.getParameter(SchoolDBSQL.MSGBODY));
                    comm2.getMessage().getDateTimeSent().setTrueValue(
                        new GregorianCalendar());
                    comm2.getMessage().getAssignedMessageID().setValue(
                        comm2.getMessageAssignedID().toString());
                }
                else {
//                  comm1.getToID().setValue(puc.getParentID().toString());
                    comm1 = ContactContainer.getContactContainer(formData.getParameter(SchoolDBSQL.MSGASSIGNEDID),
                                                                 puc.getParentID().toString(),
                                                                 formData.getParameter(SchoolDBSQL.CTFROMID),
                                                                 dbName);
                    comm1.getClassAssignedID().setValue(formData.getParameter(SchoolDBSQL.CLASSASSIGNEDID));
                    comm1.getMessage().getSubject().setValue(formData.getParameter(SchoolDBSQL.MSGSUBJECT));
                    comm1.getMessage().getMessageBody().setValue(formData.getParameter(SchoolDBSQL.MSGBODY));
                    comm1.getMessage().getDateTimeSent().setTrueValue(new GregorianCalendar());

                }
            }
            else {
                comm1 = ContactContainer.getContactContainer(formData.getParameter(SchoolDBSQL.MSGASSIGNEDID),
                                                             puc.getStudentID().toString(),
                                                             formData.getParameter(SchoolDBSQL.CTFROMID),
                                                             dbName);
                comm1.getClassAssignedID().setValue(formData.getParameter(SchoolDBSQL.CLASSASSIGNEDID));
                comm1.getMessage().getSubject().setValue(formData.getParameter(SchoolDBSQL.MSGSUBJECT));
                comm1.getMessage().getMessageBody().setValue(formData.getParameter(SchoolDBSQL.MSGBODY));
                comm1.getMessage().getDateTimeSent().setTrueValue(new GregorianCalendar());

//              comm1.getToID().setValue(puc.getStudentID().toString());
            }
        } else {
            comm1 = ContactContainer.getContactContainer(formData.getParameter(SchoolDBSQL.MSGASSIGNEDID),
                                                         formData.getParameter(SchoolDBSQL.CTTOID),
                                                         formData.getParameter(SchoolDBSQL.CTFROMID),
                                                         dbName);
            comm1.getClassAssignedID().setValue(formData.getParameter(SchoolDBSQL.CLASSASSIGNEDID));
            comm1.getMessage().getSubject().setValue(formData.getParameter(SchoolDBSQL.MSGSUBJECT));
            comm1.getMessage().getMessageBody().setValue(formData.getParameter(SchoolDBSQL.MSGBODY));
            comm1.getMessage().getDateTimeSent().setTrueValue(new GregorianCalendar());

//          comm1.getToID().setValue(formData.getParameter(SchoolDBSQL.CTTOID));
        }

        if (comm2 == null) {
            return new ContactContainer[] { comm1 };
        }
        else {
            return new ContactContainer[] { comm1, comm2 };
        }
    }

    /**
     * Parses contact information from a form and returns contact containers for each
     * sender-recipient pair.
     * @param formData The data from the form.
     * @param message The message container for which contacts are to be generated.
     * @return Contacts information for the message
     */
    public static ContactContainer[] createContacts(HttpServletRequest formData, MessageContainer message, String dbName) {
        String toIDs[] = parseList(formData.getParameter(ASSIGNEDRECIPIENTS));
        ContactContainer returnVal[] = new ContactContainer[toIDs.length];

        for (int i = 0; i < toIDs.length; i++) {
            returnVal[i] = ContactContainer.getContactContainer(formData.getParameter(SchoolDBSQL.CLASSASSIGNEDID),
                                                                toIDs[i],
                                                                formData.getParameter(SchoolDBSQL.CTFROMID),
                                                                message,
                                                                dbName);
        }

        return returnVal;
    }

    /**
     * Parses information from a form into the passed-in container
     * @param formData The data from the form.
     * @param message The message to be populated.
     */
    public static void updateMessage(HttpServletRequest formData, MessageContainer message) {
        message.getSubject().setValue(formData.getParameter(SchoolDBSQL.MSGSUBJECT));
        message.getMessageBody().setValue(formData.getParameter(SchoolDBSQL.MSGBODY));
        message.getDateTimeSent().setTrueValue(new GregorianCalendar());
    }

    /**
     * Parses information from a form into the passed-in container
     * @param formData The data from the form.
     * @param homework The container to parse into.
     */
    public static void updateHomework(
        HttpServletRequest formData,
        HomeworkContainer homework, String dataSource) {
        String hwID = (String) formData.getParameter(SchoolDBSQL.HWASSIGNEDID);
        boolean newHomework = "-1".equals(hwID);
        if (!newHomework) {
            homework = HomeworkContainer.getHomeworkContainer(hwID, dataSource);
//          homework.getHomeworkID().setValue(hwID);
        }
        homework.getClassID().setValue(formData.getParameter(SchoolDBSQL.CLASSASSIGNEDID));
        homework.getShortName().setValue(formData.getParameter(SchoolDBSQL.HWSHORTNAME));
        homework.getDescription().setValue(formData.getParameter(SchoolDBSQL.HWDESCRIPTION));
        homework.getTotalPoints().setValue(formData.getParameter(SchoolDBSQL.HWTOTALPOINTS));
        homework.getDateAssigned().setValue(formData.getParameter(SchoolDBSQL.HWDATEASSIGNED));
        homework.getDateDue().setValue(formData.getParameter(SchoolDBSQL.HWDATEDUE));
        homework.getShortName().setValue(formData.getParameter(SchoolDBSQL.HWSHORTNAME));
        homework.getAnswers().setValue(formData.getParameter(SchoolDBSQL.HWANSWERS));
        homework.getNotes().setValue(formData.getParameter(SchoolDBSQL.HWNOTES));
        homework.getSubmissionsAllowed().setValue(formData.getParameter(SchoolDBSQL.HWSUBMISSIONSALLOWED));
        if (homework.getSubmissionsAllowed().booleanValue()) {
            UserContainer students[] = SchoolDBSQL.getSchoolDBSQL(dataSource).loadStudentsInClass(homework.getClassID());
            for (int i = 0; i < students.length; ++i) {
                SubmissionContainer submission = SubmissionContainer.getSubmissionContainer(homework.getClassID().toString(),
                                                                                            homework.getHomeworkID().toString(),
                                                                                            students[i].getAssignedID().toString(),
                                                                                            dataSource);
                submission.getUpdateAllowed().setValue("TRUE");
                SchoolDBSQL.getSchoolDBSQL(dataSource).save(submission);
            }
        }
        homework.getDateUpdated().setTrueValue(new GregorianCalendar());
    }

    /**
     * Parses information from a form into the passed-in container
     * @param formData The data from the form.
     * @param homework The container to parse into.
     */
    public static HomeworkContainer updateHomework(
        HttpServletRequest formData, String dataSource) {
        String hwID = (String) formData.getParameter(SchoolDBSQL.HWASSIGNEDID);
        HomeworkContainer homework = null;
        if (!"-1".equals(hwID)) {
            homework = HomeworkContainer.getHomeworkContainer(hwID, dataSource);
        }
        else {
            homework = HomeworkContainer.getHomeworkContainer("-1", dataSource);
        }

        boolean originalSubmissionAllowed = homework.getSubmissionsAllowed().booleanValue();

        homework.getClassID().setValue(formData.getParameter(SchoolDBSQL.CLASSASSIGNEDID));
        homework.getShortName().setValue(formData.getParameter(SchoolDBSQL.HWSHORTNAME));
        homework.getDescription().setValue(formData.getParameter(SchoolDBSQL.HWDESCRIPTION));
        homework.getTotalPoints().setValue(formData.getParameter(SchoolDBSQL.HWTOTALPOINTS));
        homework.getDateAssigned().setValue(formData.getParameter(SchoolDBSQL.HWDATEASSIGNED));
        homework.getDateDue().setValue(formData.getParameter(SchoolDBSQL.HWDATEDUE));
        homework.getShortName().setValue(formData.getParameter(SchoolDBSQL.HWSHORTNAME));
        homework.getAnswers().setValue(formData.getParameter(SchoolDBSQL.HWANSWERS));
        homework.getNotes().setValue(formData.getParameter(SchoolDBSQL.HWNOTES));
        homework.getSubmissionsAllowed().setValue(formData.getParameter(SchoolDBSQL.HWSUBMISSIONSALLOWED));
        if (homework.getSubmissionsAllowed().booleanValue() && !originalSubmissionAllowed) {
            UserContainer students[] = SchoolDBSQL.getSchoolDBSQL(dataSource).loadStudentsInClass(homework.getClassID());
            for (int i = 0; i < students.length; ++i) {
                SubmissionContainer submission = SubmissionContainer.getSubmissionContainer(homework.getClassID().toString(),
                                                                                            homework.getHomeworkID().toString(),
                                                                                            students[i].getAssignedID().toString(),
                                                                                            dataSource);
                submission.getUpdateAllowed().setValue("TRUE");
                SchoolDBSQL.getSchoolDBSQL(dataSource).save(submission);
            }
        }
        homework.getDateUpdated().setTrueValue(new GregorianCalendar());

        return homework;
    }


    /**
     * Parses information from a form into the passed-in container
     * @param formData The data from the form.
     * @param student The container to parse into.
     */
    public static void updateStudent(HttpServletRequest formData, UserContainer student, String schoolName) throws IOException {
        student.getAssignedID().setValue(formData.getParameter(SchoolDBSQL.USRASSIGNEDID));
        student.getSchoolID().setValue(formData.getParameter(SchoolDBSQL.USRSCHOOLID));
        student.getFirstName().setValue(formData.getParameter(SchoolDBSQL.USRFNAME));
        student.getLastName().setValue(formData.getParameter(SchoolDBSQL.USRLNAME));
        student.getPhone().setValue(formData.getParameter(SchoolDBSQL.USRPHONE));
        student.getPassword().setValue(formData.getParameter(SchoolDBSQL.USRPASSWORD));
        student.getEmail().setValue(formData.getParameter(SchoolDBSQL.USREMAIL));
        student.getType().setValue(formData.getParameter(SchoolDBSQL.USRTYPE));
        student.getTitle().setValue(formData.getParameter(SchoolDBSQL.USRTITLE));
        if (student.getPassword() != null && !student.getPassword().isEmpty()) {
            student.getPasswordChangeRequired().setValue("TRUE");

        }
        String originalFileName = formData.getParameter(SchoolDBSQL.USRPICTURENAME +".filename");
        if (null != originalFileName && !"".equals(originalFileName)) {
            String tempFileName = formData.getParameter(SchoolDBSQL.USRPICTURENAME +".file");
            String newFileName = "";
            int extStart = originalFileName.lastIndexOf(".");
            // TODO add exception thrown here if there is no exception
            // TODO add checking for valid extensions?
            if (extStart < 0) {
                newFileName = student.getAssignedID().toString();
            }
            else {
                newFileName = student.getAssignedID() + originalFileName.substring(extStart);
            }

            try {
                File newFile = new File(newFileName);
                student.getPictureName().setValue(newFileName);
                FileInputStream is = new FileInputStream(tempFileName);
                String fullPath = "attachments" + ConfigurationItems.PATHSEPARATOR + schoolName + ConfigurationItems.PATHSEPARATOR +
                                                    "PICTURES" + ConfigurationItems.PATHSEPARATOR + newFileName;

                File newOutFilePath = new File(ConfigurationItems.BASEPATH + fullPath);
                FileOutputStream out = new FileOutputStream(newOutFilePath);

                int ch;
                while ((ch = is.read()) >= 0){
                    out.write((char) ch);
                }

                is.close();
                out.close();
            }
            catch (IOException ioe) {
                SchoolLogger.logger.log(Level.WARNING, "Could not save file: " + ioe);
                throw ioe;
            }

        }
    }

    /**
     * Parses information from a form into the passed-in container
     * @param formData The data from the form.
     * @param user The container to parse into.
     */
    public static void updateUser(HttpServletRequest formData, UserContainer user) {
        user.getAssignedID().setValue(formData.getParameter(SchoolDBSQL.USRASSIGNEDID));
        user.getSchoolID().setValue(formData.getParameter(SchoolDBSQL.USRSCHOOLID));
        user.getFirstName().setValue(formData.getParameter(SchoolDBSQL.USRFNAME));
        user.getLastName().setValue(formData.getParameter(SchoolDBSQL.USRLNAME));
        user.getPhone().setValue(formData.getParameter(SchoolDBSQL.USRPHONE));
        user.getPassword().setValue(formData.getParameter(SchoolDBSQL.USRPASSWORD));
        user.getEmail().setValue(formData.getParameter(SchoolDBSQL.USREMAIL));
        user.getType().setValue(formData.getParameter(SchoolDBSQL.USRTYPE));
        user.getTitle().setValue(formData.getParameter(SchoolDBSQL.USRTITLE));
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.getPasswordChangeRequired().setValue("TRUE");

        }
    }

    /**
     * Parses a comma delimited list of class IDs and returns a list of items containing the
     * IDs contained in the list.
     * @param listOfClasses A string representation of class IDs
     * @return An array of Items containing all classes contained in listOfClasses
     */
    public static Item[] parseClassList(String listOfClasses) {
        ArrayList al = new ArrayList();
        int index = -1;
        while ((index = listOfClasses.indexOf(",")) != -1) {
            al.add(new StringItem(SchoolDBSQL.CLASSASSIGNEDID, listOfClasses.substring(0, index), false));
            listOfClasses = listOfClasses.substring(index + 1);
        }
        if (listOfClasses.length() > 0)
            al.add(new StringItem(SchoolDBSQL.CLASSASSIGNEDID, listOfClasses, false));
        return (Item[]) al.toArray(new Item[] {});
    }

    /**
     * Parses a comma delimited list of IDs and returns a list of items containing
     * the IDs contained in the list.
     * @param list A string representation of a list
     * @return An array of Strings contained in the input string
     */
    public static String[] parseList(String list) {

        ArrayList al = new ArrayList();
        int index = -1;
        while ((index = list.indexOf(",")) != -1) {
            al.add(list.substring(0, index));
            list = list.substring(index + 1);
        }
        if (list.length() > 0) {
            al.add(list);
        }

        return (String[]) al.toArray(new String[] {});
    }

    /**
     * Parses information from a form into the passed-in container
     * @param formData The data from the form.
     * @param classContainer The container to parse into.
     */
    public static void updateTeacher(HttpServletRequest formData, UserContainer teacher) {
        teacher.getAssignedID().setValue(formData.getParameter(SchoolDBSQL.USRASSIGNEDID));
        teacher.getSchoolID().setValue(formData.getParameter(SchoolDBSQL.USRSCHOOLID));
        teacher.getFirstName().setValue(formData.getParameter(SchoolDBSQL.USRFNAME));
        teacher.getLastName().setValue(formData.getParameter(SchoolDBSQL.USRLNAME));
        teacher.getPhone().setValue(formData.getParameter(SchoolDBSQL.USRPHONE));
        teacher.getPassword().setValue(formData.getParameter(SchoolDBSQL.USRPASSWORD));
        teacher.getEmail().setValue(formData.getParameter(SchoolDBSQL.USREMAIL));
        teacher.getType().setValue(formData.getParameter(SchoolDBSQL.USRTYPE));
        teacher.getTitle().setValue(formData.getParameter(SchoolDBSQL.USRTITLE));
        if (teacher.getPassword() != null && !teacher.getPassword().isEmpty()) {
            teacher.getPasswordChangeRequired().setValue("TRUE");

        }
    }

    /**
     * Validates two passwords match and parses the first password into the passed-in container
     * @param formData The data from the form.
     * @param newPI The container to parse into.
     */
    public static void getNewPassword(HttpServletRequest formData, PasswordItem newPI) {
        String newPassword = formData.getParameter(NEWPASSWORD);
        String renewPassword = formData.getParameter(NEWPASSWORD);
        if (newPassword != null && newPassword.equals(renewPassword)) {
            newPI.setValue(newPassword);
        } else {
            newPI.setTrueValue(null);
        }
    }
}
